package com.hunktimes.wholesale.mock

import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.hunktimes.wholesale.App
import com.hunktimes.wholesale.net.model.MockGoods
import com.hunktimes.wholesale.util.L
import java.io.BufferedReader
import java.io.InputStreamReader

/**
 * Author: Delete
 * Date: 2020/9/15 14:37
 * Description:
 *
 */
object MockJsonParser {
    lateinit var goods: List<MockGoods>
    lateinit var jewels: List<MockGoods>
    private val gson = Gson()
    fun parserGoods(app: App) {
        var result = ""
        try {
            val sb = StringBuilder()
            val assetsManager = app.applicationContext.assets
            val ins = InputStreamReader(assetsManager.open("goods.json"))
            val bfReader = BufferedReader(ins)
            var line: String? = null
            while (bfReader.readLine().also({ line = it }) != null) {
                sb.append(line)
            }
            result = sb.toString()
            L.d("parserGoods -> $result")
        } catch (e: Exception) {
            L.d("parserGoods  error -> ${e.message}")
        }
        if (result.isNotBlank()) {
             goods = gson.fromJson<List<MockGoods>>(result, object :
                TypeToken<List<MockGoods>>() {}.type)
            L.d("parserGoods goods -> $goods")
        }
    }

    fun parseJewels(app: App) {
        var result = ""
        try {
            val sb = StringBuilder()
            val assetsManager = app.applicationContext.assets
            val ins = InputStreamReader(assetsManager.open("jewel.json"))
            val bfReader = BufferedReader(ins)
            var line: String? = null
            while (bfReader.readLine().also({ line = it }) != null) {
                sb.append(line)
            }
            result = sb.toString()
            L.d("parseJewels -> $result")
        } catch (e: Exception) {
            L.d("parseJewels  error -> ${e.message}")
        }
        if (result.isNotBlank()) {
            jewels = gson.fromJson<List<MockGoods>>(result, object :
                TypeToken<List<MockGoods>>() {}.type)
            L.d("parseJewels jewels -> $jewels")
        }
    }
}